package com.jhx.video.comment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.RadioGroup
import android.widget.TextView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.utils.DisplayUtil
import com.jhx.common.utils.ImageLoader
import com.jhx.common.utils.UserManager
import com.jhx.common.utils.centerToast
import com.jhx.video.R
import com.jhx.video.discuss.DiscussActivity
import com.jhx.video.discuss.DiscussFragment
import com.jhx.video.model.CommentDetail
import com.jhx.video.model.CommentItem
import com.jhx.video.widget.ReplyDialog
import kotlinx.android.synthetic.main.fragment_comment.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * 店铺所有评论
 *
 * @author Jack 2018-03-28 17:11
 */
class CommentFragment : QuickBaseFragment(), Contract.AllCommentView {
    private var mAdapter: BaseQuickAdapter<CommentDetail, BaseViewHolder>? = null
    private var mCommentData: ArrayList<CommentDetail>? = null
    private var mPresenter: CommentPresenterImpl? = null
    private var mCommentType: Int = TYPE_I_COMMENT
    private var mReplyDialog: ReplyDialog? = null
    private var mCommentRg: RadioGroup? = null
    private var mWindow: PopupWindow? = null
    private var mEmptyView: View? = null
    private var mPageIndex = 1
    private var mPageSize = 10
    private var mType = 0

    companion object {
        val KEY_FORM = "form_page"
        // 店铺评论
        val TYPE_STORE_COMMENT = 1
        // 我收到的
        val TYPE_I_RECEIVED = 1
        // 我回复的
        val TYPE_I_COMMENT = 2

        fun newInstance(type: Int): CommentFragment {
            val fragment = CommentFragment()
            val bundle = Bundle()
            bundle.putInt(KEY_FORM, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_comment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mEmptyView = view?.findViewById(R.id.empty_layout)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        if(arguments != null) {
            mType = arguments?.getInt(KEY_FORM) ?: 0
            if(mType == TYPE_STORE_COMMENT) {
                mEmptyView?.visibility = View.VISIBLE
                refresh_layout.visibility = View.GONE
                toolbar.visibility = View.GONE
                return
            }
        }
        mPresenter = CommentPresenterImpl()
        mPresenter?.setView(this)
        mPresenter?.getComment(mCommentType, mPageIndex, mPageSize)
        initListener()
        initRecyclerView()
    }

    private fun initListener() {
        toolbar_title.setOnClickListener {
            if(mWindow == null) {
                mWindow = PopupWindow(activity)
                val view = LayoutInflater.from(activity).inflate(R.layout.window_comment, null)
                mWindow?.contentView = view
                mWindow?.width = DisplayUtil.dip2px(activity, 150f)
                mCommentRg = view.findViewById(R.id.rg_comment)
                mCommentRg?.setOnCheckedChangeListener { _, checkedId ->
                    when(checkedId) {
                        R.id.rb_received -> {
                            mCommentType = TYPE_I_RECEIVED
                            toolbar_title.text = "我收到的"
                        }
                        R.id.rb_comment -> {
                            mCommentType = TYPE_I_COMMENT
                            toolbar_title.text = "我回复的"
                        }
                    }
                    mWindow?.dismiss()
                    mPageIndex = 1
                    mPresenter?.getComment(mCommentType, mPageIndex, mPageSize)
                }
            }
            mWindow?.isOutsideTouchable = true
            mWindow?.setBackgroundDrawable(null)
            mWindow?.showAsDropDown(toolbar_title)
        }
        refresh_layout.setOnRefreshListener {
            refresh_layout.isRefreshing = true
            mPageIndex = 1
            mPresenter?.getComment(mCommentType, mPageIndex, mPageSize)
        }
        img_back.setOnClickListener {
            pop()
        }
    }

    private fun initRecyclerView() {
        mAdapter = CommentAdapter(mCommentData)
        mAdapter?.setOnLoadMoreListener({
            mPresenter?.getComment(mCommentType, mPageIndex, mPageSize)
        }, recycler_view)
        recycler_view.adapter = mAdapter
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.addItemDecoration(DividerItemDecoration(activity, LinearLayoutManager.VERTICAL))
    }

    inner class CommentAdapter(data: MutableList<CommentDetail>?) : BaseMultiItemQuickAdapter<CommentDetail, BaseViewHolder>(data) {

        init {
            addItemType(CommentItem.ITEM_REPLY, R.layout.item_comment_layout)
            addItemType(CommentItem.ITEM_NOT_REPLY, R.layout.item_comment_reply)
        }

        override fun convert(holder: BaseViewHolder, data: CommentDetail?) {

            when(holder.itemViewType) {
                CommentItem.ITEM_NOT_REPLY -> {
                    val replyText = holder.getView<TextView>(R.id.text_reply)
                    ImageLoader.get().loadCircleImageByUrl(activity, data?.userHeadImg, holder.getView(R.id.img_head))
                    holder.setText(R.id.txt_business_name, "${data?.userName}   回复：")
                    holder.setText(R.id.txt_reply, "${data?.context}")
                    try {
                        if(data?.createTime != null) {
                            val date = Date(data.createTime!!.toLong())
                            val time = SimpleDateFormat("MM-dd HH:mm").format(date)
                            holder.setText(R.id.txt_date, time)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    if(mCommentType == TYPE_I_RECEIVED) {
                        replyText.visibility = View.GONE
                    } else {
                        replyText.visibility = View.VISIBLE
                    }
                    replyText.setOnClickListener {
                        if(mReplyDialog == null && activity?.isFinishing == false) {
                            mReplyDialog = ReplyDialog(activity!!)
                        }
                        mReplyDialog?.dismiss()
                        mReplyDialog?.onSendClick = { msg ->
                            mPresenter?.replyComment("${data?.id}", "$msg")
                        }
                        if(activity?.isFinishing == false) {
                            mReplyDialog?.show()
                        }
                    }
                }
                CommentItem.ITEM_REPLY -> {
                    ImageLoader.get().loadCircleImageByUrl(activity,
                            UserManager.get().user.headImage,
                            holder.getView(R.id.img_head))
                    holder.setText(R.id.txt_business_name, "${data?.userName}   回复：")
                    holder.setText(R.id.txt_reply, "${data?.context}")
                    if(data?.children?.isNotEmpty() == true) {
                        holder.setText(R.id.txt_nikename, "${data.children?.get(0)?.userName}   回复：")
                        holder.setText(R.id.txt_content, "${data.children?.get(0)?.context}")
                    }
                    try {
                        if(data?.createTime != null) {
                            val date = Date(data.createTime!!.toLong())
                            val time = SimpleDateFormat("MM-dd HH:mm").format(date)
                            holder.setText(R.id.txt_date, time)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
            holder.setText(R.id.txt_user_nickname, "${data?.userName}")
            try {
                if(data?.publish_time != null) {
                    val date = Date(data.publish_time!!.toLong())
                    val time = SimpleDateFormat("MM-dd HH:mm").format(date)
                    holder.setText(R.id.txt_create_time, time)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            holder.setText(R.id.txt_play_num, "${data?.play_num}")
            holder.setText(R.id.txt_video_content, "${data?.v_title}")
            ImageLoader.get().loadImageByUrl(activity, "${data?.cover_url}", holder.getView(R.id.player))
            holder.getView<ConstraintLayout>(R.id.cl_item).setOnClickListener {
                val intent = Intent(activity, DiscussActivity::class.java)
                intent.putExtra(DiscussFragment.KEY_VIDEO_ID, data?.SVId)
                startActivity(intent)
            }
        }

    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun hideLoading() {
        hideLoadingDialog()
    }

    override fun getCommentSuccess(data: List<CommentDetail>?) {
        if(data?.isNotEmpty() == true) {
            mEmptyView?.visibility = View.GONE
            refresh_layout.visibility = View.VISIBLE
            if(mPageIndex == 1) {
                refresh_layout.isRefreshing = false
                mAdapter?.data?.clear()
            } else {
                mAdapter?.loadMoreComplete()
            }
            data.forEach {
                if(mCommentType == TYPE_I_COMMENT) {
                    if(it.children?.isNotEmpty() == true) {
                        it.setType(CommentItem.ITEM_REPLY)
                    } else {
                        it.setType(CommentItem.ITEM_NOT_REPLY)
                    }
                } else {
                    it.setType(CommentItem.ITEM_NOT_REPLY)
                }
            }
            mAdapter?.data?.addAll(data)
            mAdapter?.notifyDataSetChanged()
            mPageIndex ++
        } else {
            if(mPageIndex == 1) {
                refresh_layout.isRefreshing = false
                mEmptyView?.visibility = View.VISIBLE
                refresh_layout.visibility = View.GONE
            } else {
                mAdapter?.loadMoreEnd()
            }
        }
    }

    override fun getContext(): Activity {
        return activity!!
    }

    override fun replyCommentSuccess() {
        activity?.centerToast("回复成功~")
        mPageIndex = 1
        mPresenter?.getComment(mCommentType, mPageIndex, mPageSize)
    }

    override fun requestError() {
        hideLoading()
        mAdapter?.loadMoreComplete()
        refresh_layout.isRefreshing = false
    }
}